<template>
  <div class="model-panel-body">
    <!-- 条件栏 -->
    <page-filter :filter-list="filterInfo.list">
      <template v-slot:filter-scanCode>
        <div class="scan-input-box">
          <ScanInputBox
            :tableData="tableInfo.data"
            v-model:query="scanFilter"
            :api="scanApi"
            @callback="onCallBackScanData"
          />
        </div>
      </template>
    </page-filter>
    <div class="flex_full_item">
      <!-- 表格 -->
      <el-form
        :model="tableInfo"
        :rules="tableInfo.rules"
        ref="tableForm"
        style="width: 100%"
      >
        <page-table
          :init-curpage="tableInfo.initCurpage"
          v-model:data="tableInfo.data"
          :tabIndex="true"
          :pager="false"
          :mergeData="tableInfo.mergeData"
          :mergeFiled="tableInfo.mergeFiled"
          v-model:query="filterInfo.query"
          :field-list="tableInfo.fieldList"
          :handle="tableInfo.handle"
          @handleEvent="handleEvent"
        >
          <template v-slot:col-licenseNumber="scope">
            <p>{{ scope.row.licenseNumber || '-' }}</p>
            <p>{{ scope.row.brandName || '-' }}</p>
          </template>
          <!--<template v-slot:col-serialNumber="scope">
            <p>{{scope.row.serialNumber || scope.row.unityCode}}</p>
          </template>-->
          <template v-slot:col-commonName="scope">
            <p>{{ scope.row.commonName || '-' }}</p>
            <p>{{ scope.row.productCode || '-' }}</p>
            <p>{{ scope.row.alias || '-' }}</p>
          </template>
          <template v-slot:col-type="scope">
            <p>{{ scope.row.productTypeValue || '-' }}</p>
            <p>{{ scope.row.codeTypeValue || '-' }}</p>
            <p>{{ scope.row.productCategoryValue || '-' }}</p>
          </template>
          <template v-slot:col-standard="scope">
            <p>{{ scope.row.standard || '-' }}</p>
            <p>{{ scope.row.unitName || '-' }}</p>
          </template>
          <template v-slot:col-batchNumber="scope">
            <el-input
              v-model="scope.row.batchNumber"
              :maxlength="25"
              @change="changeData($event, scope.row, scope.$index)"
              @input="(e) => (scope.row.batchNumber = validSe(e))"
            />
          </template>
          <template v-slot:col-productionDate="scope">
            <el-date-picker
              v-model="scope.row.productionDate"
              value-format="YYYY-MM-DD"
              :disabled-date="productionTimePickerOptions.disabledDate"
              @change="changeData($event, scope.row, scope.$index)"
            />
          </template>
          <template v-slot:col-validityDate="scope">
            <el-date-picker
              v-model="scope.row.validityDate"
              value-format="YYYY-MM-DD"
              :disabled-date="validityTimePickerOptions.disabledDate"
              @change="changeData($event, scope.row, scope.$index)"
            />
          </template>

          <template v-slot:col-serialNumber="scope">
            <el-input
              v-model="scope.row.serialNumber"
              :maxlength="25"
              @change="changeData($event, scope.row, scope.$index)"
              @input="(e) => (scope.row.serialNumber = validSe(e))"
            />
          </template>
        </page-table>
      </el-form>
    </div>
    <!-- 选择库存产品 -->
    <select-product
      v-if="selectedProduct.visible"
      v-model:show-dialog="selectedProduct.visible"
      v-model:query="selectedProduct.query"
      :api="selectedProduct.api"
      @callback="selectedProductCallback"
    />
  </div>
</template>

<script setup name="AddPrintQRcode">
import PageFilter from '@/components/PageFilter/index'
import PageTable from '@/components/PageTable/index'
import { getDepotStoragePage } from '@/api/stock'
import { getProductPage } from '@/api/core'
import { postPrintQrCodeScan } from '@/api/core'
import ScanInputBox from './ScanInputBox'
import SelectProduct from '@/components/SelectProduct/index'
const { proxy } = getCurrentInstance()
const props = defineProps({
  selections: {
    type: Array,
    default: function () {
      return []
    },
  },
})
const productionTimePickerOptions = ref({
  disabledDate(time) {
    return time.getTime() > Date.now() - 8.64e6
  },
})
const validityTimePickerOptions = ref({
  disabledDate(time) {
    return time.getTime() < Date.now() - 24 * 60 * 60 * 1000
  },
})
const code = ref('')
const scanFilter = ref({})
const scanApi = ref(postPrintQrCodeScan)
const filterInfo = ref({
  list: [
    { type: 'button', label: '添加产品', event: addProduct },
    { type: 'button', label: '删除产品', event: removeProduct },
    { type: 'slot', value: 'scanCode' },
  ],
})
const printerInfo = ref({
  visible: false,
  data: {},
})
// 表格相关
const tableInfo = ref({
  refresh: 1,
  initCurpage: 1,
  data: [],
  api: getDepotStoragePage,
  selections: [],
  mergeFiled: ['licenseNumber', 'commonName', 'type', 'standard'],
  mergeData: {},
  fieldList: [
    {
      label: '通用名称\n编码\n别名',
      value: 'commonName',
      type: 'slot',
      minWidth: '220px',
    },
    {
      label: '产品类型\n条码类型\n产品分类',
      value: 'type',
      type: 'slot',
      minWidth: '150px',
    },
    { label: '规格\n计量单位', value: 'standard', type: 'slot' },
    { label: '供应商', value: 'supplierName', type: 'text' },
    {
      label: '价格',
      value: 'price',
      type: 'column',
      formatter: proxy.$fn.TripartiteMethod,
    },
    { label: '生产批号', value: 'batchNumber', type: 'slot' },
    { label: '生产日期', value: 'productionDate', type: 'slot' },
    { label: '失效日期', value: 'validityDate', type: 'slot' },
    {
      label: '数量',
      value: 'qty',
      type: 'number2',
      width: '120px',
      formatter: proxy.$fn.qtyFormatter,
    },
    {
      label: '原厂唯一码\n个体码',
      value: 'serialNumber',
      type: 'slot',
    },
    {
      label: '证号\n生产厂家',
      value: 'licenseNumber',
      type: 'slot',
      minWidth: '220px',
    },
  ],
  rules: {
    serialNumber: [{ required: false }],

    batchNumber: [{ required: true, message: '批号不能为空', trigger: 'blur' }],
    productionDate: [
      {
        type: 'date',
        required: true,
        message: '请选择生产日期',
        trigger: 'change',
      },
    ],
    validityDate: [
      {
        type: 'date',
        required: true,
        message: '请选择失效日期',
        trigger: 'change',
      },
    ],
    qty: [{ validator: proxy.$validate.positive, trigger: 'blur' }],
  },
  handle: {
    fixed: 'right',
    label: '操作',
    width: '80',
    btList: [
      {
        label: '打印二维码',
        event: onPrintQRcode,
        show: true,
        ifRender: function (row) {
          return row.oneToOneMode == 'system'
        },
      },
      {
        label: '生成条码',
        event: onGenerateCode,
        show: true,
        ifRender: function (row) {
          console.log(row)
          return row.oneToOneMode == 'origin'
        },
      },
    ],
  },
})
const selectedProduct = ref({
  visible: false,
  api: getProductPage,
  query: {
    idNotIn: '',
    deptResourceProduct: true,
    needPrintType: 'system',
    type: 0,
  },
})

watch(
  () => tableInfo.value.data,
  (val) => {
    tableInfo.value.mergeData = proxy.$fn.getMergeData(val)
  },
  { deep: true }
)
watch(
  () => props.selections,
  (val) => {
    console.log(val)
    if (val) {
      tableInfo.value.data.forEach((item, index) => {
        val.forEach((selectItem) => {
          if (item.productCode === selectItem.productCode) {
            tableInfo.value.data[index] = selectItem
          }
        })
      })
    }
  },
  { deep: true }
)

function generateProductKey(products) {
  return products.map((item) => {
    const key =
      item.productId +
      '&' +
      item.batchNumber +
      '&' +
      item.validityDate +
      '&' +
      item.productionDate
    item._id = key
    return item
  })
}
function onCallBackScanData(stateProduct) {
  if (!stateProduct.flag) {
    stateProduct.data = {
      ...stateProduct.data,
      productionDate: stateProduct.data.productionDate || undefined,
      validityDate: stateProduct.data.validityDate || undefined,
    }
    tableInfo.value.data.push(stateProduct.data)
  }
  tableInfo.value.data.sort((a, b) => {
    return b.productId - a.productId
  })
}
function onPrintQRcode(row) {
  emits('handlePrintQRcode', row)
}
function onGenerateCode(row) {
  emits('handleGenerateCode', row)
}
function printerCallBack(printer) {
  if (printer !== false) {
    proxy.$print.buildRenderBarCode(printerInfo.value.data, printer)
  }
  printerInfo.value.visible = false
}
// 获取列表
function getList() {
  tableInfo.value.refresh = Math.random()
}
// 触发事件
function handleEvent(event, data) {
  switch (event) {
    case 'tableCheck':
      tableInfo.value.selections = [...data]
      emits('callback', tableInfo.value)
      break
  }
}
//删除产品
function removeProduct() {
  tableInfo.value.data = tableInfo.value.data.filter(
    (value) => !tableInfo.value.selections.includes(value)
  )
  selectedProduct.value.query.idNotIn = getIdNotIn(tableInfo.value.data)
}
//添加产品
function addProduct() {
  selectedProduct.value.query.idNotIn = getIdNotIn(tableInfo.value.data)
  selectedProduct.value.visible = true
}
function selectedProductCallback(data) {
  data = generateProductKey(data)
  if (data.length) {
    tableInfo.value.data = data
      .map((value) => {
        return {
          ...value,
          qty: 1,
          id: value.id,
        }
      })
      .concat(tableInfo.value.data)
  }
}
function getIdNotIn(data) {
  //获取选择产品列表时排除已选的id
  const productIds = data.map((item) => item.productId)
  let idNotIn = ''
  if (productIds.length) {
    const productIdsSet = new Set(productIds)
    idNotIn = [...productIdsSet].toString()
  }
  return idNotIn
}
function changeData(evet, row, index) {
  //批号效期改变更新_id
  let item = tableInfo.value.data.filter((item, i) => i === index)
  const key =
    item.productId +
    '&' +
    item.batchNumber +
    '&' +
    item.validityDate +
    '&' +
    item.productionDate
  tableInfo.value.data[index] = {
    ...tableInfo.value.data[index],
    _id: key,
  }
}
</script>

<style scoped lang="scss">
:deep(.page-table > .el-table) {
  overflow: hidden;
}
</style>
